package com.cps.platform.core.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.cps.platform.core.exception.PlatFormException;

/**
 * <p>
 * 文件名称: ReadProperties.java
 * </p>
 * <p>
 * 文件描述: 获取配置属性信息
 * <p>
 * 版权所有: 版权所有(C)2011
 * </p>
 * <p>
 * 公 司: 联通系统集成有限公司
 * </p>
 * <p>
 * 完成日期：2012-12-13
 * </p>
 * 
 * @author ChenZhang
 */
public class ReadProperties {

	private static Logger log = Logger.getLogger(ReadProperties.class);
	private Properties config = null;
	private String propertyFileName;
	
	public ReadProperties(String propertyFileName){
		this.propertyFileName = propertyFileName;
		this.init(propertyFileName);
	}
	
	private void init(String propertyFileName) {
		InputStream in = ReadProperties.class.getClassLoader()
				.getResourceAsStream(propertyFileName);
		config = new Properties();
		try {
			config.load(in);
			in.close();
		} catch (IOException e) {
			log.error("No "+propertyFileName+" defined error");
		}
	}

	/**
	 * 根据key读取value
	 * 
	 * @param key
	 * @return
	 */
	public String readValue(String key) {
		try {
			String value = config.getProperty(key);
			return value;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("ConfigInfoError" + e.toString());
			return null;
		}
	}
	
	/**
	 * 设置配置属性
	 * @param key
	 * @param value
	 */
	public synchronized void setProperty(String key, String value){
		config.setProperty(key, value);
		String filePath = ReadProperties.class.getResource("/").getPath();
		
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(filePath + propertyFileName);
			config.store(fos, "");
		} catch (FileNotFoundException e) {
			log.error("No "+propertyFileName+" defined error. "+ e.getMessage());
			throw new PlatFormException(e.getMessage());
		} catch (IOException e) {
			log.error("File "+propertyFileName+" io error. "+ e.getMessage());
			throw new PlatFormException(e.getMessage());
		} finally {
			if(fos!=null)
				try {
					fos.close();
				} catch (IOException e) {}
		}
	}

	public String getPropertyFileName() {
		return propertyFileName;
	}

	public void setPropertyFileName(String propertyFileName) {
		this.propertyFileName = propertyFileName;
	}
}